package com.sl.plugin.step.selenium.console;

import cn.hutool.core.util.ObjectUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import lombok.SneakyThrows;
import org.openqa.selenium.SessionNotCreatedException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;

import java.util.logging.Level;

/**
 *
 */
public class SeleniumConsoleComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {

    public SeleniumConsoleComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @SneakyThrows
    @Override
    public WebDriver input(WebDriver driver) {
        String level = meta.getStrAttr("level");
        Level parse = Level.parse(level);

        Boolean wile = true;
        while (wile) {
            if (ObjectUtil.isNull(driver)) {
                return driver;
            }
            try {
                // 调用一个无副作用的方法（如获取当前窗口句柄）
                driver.getWindowHandle();
                wile = false; // 未退出
            } catch (SessionNotCreatedException e) {
                wile = true; // 已退出
            } catch (Exception e) {
                // 其他异常（如浏览器崩溃）也视为退出
                wile = true;
            }
            try {
                // 4. 执行操作后，获取浏览器控制台日志
                LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);

                // 5. 遍历日志，检查是否有错误
                boolean hasConsoleError = false;
                for (LogEntry entry : logEntries) {
                    // 日志级别为SEVERE的即为错误
                    if (entry.getLevel() == parse) {
                        hasConsoleError = true;
                        logBasic("时间：" + entry.getTimestamp()+"信息：" + entry.getMessage()+"级别：" + entry.getLevel());
                    }
                }

                if (!hasConsoleError) {
                    System.out.println("未检测到控制台控制台错误");
                }

            } finally {
                // 关闭浏览器
            }
        }


        return driver;
    }

}
